package com.ruoyi.info.userController;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.info.domain.FhInfoTasklist;
import com.ruoyi.info.domain.FhInfoUsertask;
import com.ruoyi.info.service.IFhInfoTasklistService;
import com.ruoyi.info.service.IFhInfoUserService;
import com.ruoyi.info.service.IFhInfoUsertaskService;
import com.ruoyi.info.utils.PointsUtil;
import com.ruoyi.tokenTools.UserLoginToken;
import com.ruoyi.web.core.config.LocalUserInfoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 任务控制器
 */
@Api(tags = "任务接口")
@RestController
@RequestMapping("/app/task")
public class TaskController extends BaseController {

    @Autowired
    private IFhInfoTasklistService fhInfoTasklistService;

    @Autowired
    private IFhInfoUsertaskService fhInfoUsertaskService;

    @Autowired
    private PointsUtil pointsUtil;

    /**
     * 任务VO
     */
    public static class TaskVO {
        /** 任务ID */
        private Long taskId;
        
        /** 任务名 */
        private String task;
        
        /** 任务详情 */
        private String details;
        
        /** 积分 */
        private Long point;
        
        /** 任务类型 */
        private String taskType;
        
        /** 图片 */
        private String image;
        
        /** 当天完成数量 */
        private Integer completedCount;
        
        /** 是否完成（达到5次） */
        private Boolean isCompleted;
        
        /** 是否已领取积分 */
        private Boolean isRewardReceived;

        public Long getTaskId() {
            return taskId;
        }

        public void setTaskId(Long taskId) {
            this.taskId = taskId;
        }

        public String getTask() {
            return task;
        }

        public void setTask(String task) {
            this.task = task;
        }

        public String getDetails() {
            return details;
        }

        public void setDetails(String details) {
            this.details = details;
        }

        public Long getPoint() {
            return point;
        }

        public void setPoint(Long point) {
            this.point = point;
        }

        public String getTaskType() {
            return taskType;
        }

        public void setTaskType(String taskType) {
            this.taskType = taskType;
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public Integer getCompletedCount() {
            return completedCount;
        }

        public void setCompletedCount(Integer completedCount) {
            this.completedCount = completedCount;
        }

        public Boolean getIsCompleted() {
            return isCompleted;
        }

        public void setIsCompleted(Boolean isCompleted) {
            this.isCompleted = isCompleted;
        }

        public Boolean getIsRewardReceived() {
            return isRewardReceived;
        }

        public void setIsRewardReceived(Boolean isRewardReceived) {
            this.isRewardReceived = isRewardReceived;
        }
    }

    /**
     * 查询当天所有任务（包含完成数量、是否完成）
     */
    @UserLoginToken
    @ApiOperation("查询当天所有任务")
    @GetMapping("/today")
    public R<List<TaskVO>> getTodayTasks() {
        try {
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            
            // 查询所有任务
            List<FhInfoTasklist> taskList = fhInfoTasklistService.selectFhInfoTasklistList(new FhInfoTasklist());
            
            List<TaskVO> result = new ArrayList<>();
            for (FhInfoTasklist task : taskList) {
                TaskVO taskVO = new TaskVO();
                taskVO.setTaskId(task.getId());
                taskVO.setTask(task.getTask());
                taskVO.setDetails(task.getDetails());
                taskVO.setPoint(task.getPoint());
                taskVO.setTaskType(task.getTaskType());
                taskVO.setImage(task.getImage());
                
                // 查询当天完成数量
                int count = fhInfoUsertaskService.countTodayTaskLog(userId, task.getId(), today);
                taskVO.setCompletedCount(count);
                
                // 判断是否完成（达到5次）
                taskVO.setIsCompleted(count >= 5);
                
                // 查询是否已领取积分（查询当天是否有completion_status='0'的记录）
                boolean isRewardReceived = fhInfoUsertaskService.isRewardReceived(userId, task.getId(), today);
                taskVO.setIsRewardReceived(isRewardReceived);
                
                result.add(taskVO);
            }
            
            return R.ok(result);
        } catch (Exception e) {
            return R.fail("查询任务失败: " + e.getMessage());
        }
    }

    /**
     * 完成任务（领取积分）
     */
    @UserLoginToken
    @ApiOperation("完成任务")
    @PostMapping("/complete")
    public R<String> completeTask(@RequestParam Long taskId) {
        try {
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            
            // 查询当天完成数量
            int count = fhInfoUsertaskService.countTodayTaskLog(userId, taskId, today);
            
            if (count < 5) {
                return R.fail("任务未完成，需要完成5次才能领取积分");
            }
            
            // 获取任务信息
            FhInfoTasklist task = fhInfoTasklistService.selectFhInfoTasklistById(taskId);
            if (task == null) {
                return R.fail("任务不存在");
            }
            
            // 计算积分：任务次数 * 积分
            Long totalPoints = (long) count * task.getPoint();
            
            // 检查是否已经领取过积分
            boolean alreadyReceived = fhInfoUsertaskService.isRewardReceived(userId, taskId, today);
            if (alreadyReceived) {
                return R.fail("该任务积分已领取，不能重复领取");
            }
            
            // 使用工具类增加积分并记录流水
            pointsUtil.addPoints(userId, totalPoints, "task_complete", taskId, 
                "完成任务【" + task.getTask() + "】，完成次数：" + count + "次，获得积分：" + totalPoints);
            
            // 插入一条完成记录，标记为已领取积分
            FhInfoUsertask rewardRecord = new FhInfoUsertask();
            rewardRecord.setUserId(userId);
            rewardRecord.setTaskId(taskId);
            rewardRecord.setTask(task.getTask());
            rewardRecord.setDetails(task.getDetails());
            rewardRecord.setPoint(task.getPoint());
            rewardRecord.setTaskType(task.getTaskType());
            rewardRecord.setTaskTime(new Date());
            rewardRecord.setCompletionStatus("1"); // 1表示操作记录
            rewardRecord.setRewardReceived("1"); // 1表示已领取积分
            rewardRecord.setCrateTime(new Date());
            fhInfoUsertaskService.insertFhInfoUsertask(rewardRecord);
            
            return R.ok("完成任务成功，获得积分: " + totalPoints);
        } catch (Exception e) {
            return R.fail("完成任务失败: " + e.getMessage());
        }
    }
}

